package com.yourenbang.lingyun.transaction.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.yourenbang.lingyun.constants.enums.mq.transaction.FundMqDTO;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.exception.UserBizException;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.transaction.web.service.fund.FundService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 资金
 */
@Slf4j
@Component
public class FundMessageListener implements MessageListener {

    @Autowired
    private FundService fundService;

    @Override
    public Action consume(Message message, ConsumeContext context) {

        String msgkey = message.getKey();
        String dataStr = new String(message.getBody(), StandardCharsets.UTF_8);
        KLog.info("[MQ-资金账户]消息key:[{}],接收参数:{}", msgkey, dataStr);
        try {
            FundMqDTO fundMqDTO = JSONObject.parseObject(dataStr, FundMqDTO.class);
            if (StringUtils.equals(fundMqDTO.getOpt(), FundMqDTO.ACCOUNT_ADD)) {
                fundService.addFund(fundMqDTO.getData());
            } else if (StringUtils.equals(fundMqDTO.getOpt(), FundMqDTO.ACCOUNT_SUBTRACT)) {
                fundService.subtractFund(fundMqDTO.getData());
            } else if (StringUtils.equals(fundMqDTO.getOpt(), FundMqDTO.BILL)) {
//                fundService.addBill(fundMqDTO.getData());
                KLog.error("[MQ-资金账户]不支持的操作,消息key:[{}],接收参数:{}", msgkey, dataStr);
            } else {
                KLog.error("[MQ-资金账户]不支持的操作,消息key:[{}],接收参数:{}", msgkey, dataStr);
            }
            return Action.CommitMessage;
        } catch (UserBizException e) {
            KLog.error("[MQ-资金账户]业务异常:{},消息key:[{}],接收参数:{}", e.getErrorMessage(), msgkey, dataStr);
            return Action.CommitMessage;    //返回成功
        } catch (BizRuntimeException e) {
            KLog.error("[MQ-资金账户]业务异常:{},消息key:[{}],接收参数:{}", e.getErrorMessage(), msgkey, dataStr, e);
            return Action.CommitMessage;    //返回成功
        } catch (Exception e) {
            KLog.error("[MQ-资金账户]异常:{},消息key:[{}],接收参数:{}", e.getMessage(), msgkey, dataStr, e);
            return Action.ReconsumeLater;
        }
    }

}
